package com.ants.douyin.util.douyin;

import com.alibaba.fastjson.JSON;
import com.ants.douyin.util.download.DownloadUtil;
import com.ants.douyin.util.json.JsonToMapUtil;
import com.ants.douyin.vo.DouDataVO;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URLDecoder;

@Slf4j
@Component
public class DouYinUtil {

    public static String downLoad (String url) throws IOException {
        // 获取短连接码
        String sub = "https://v.douyin.com/"+url.split("https://v.douyin.com/")[1].substring(0, 7);
        // 通过短连接获取长链接
        String redirectUrl = Jsoup.connect(sub).followRedirects(true).execute().url().toString();
        // 获取itemId
        String itemId = redirectUrl.split("https://www.iesdouyin.com/share/video/")[0].split("/\\?region=")[0];
        // 重新信息页面
        String newUrl = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids="+itemId;
        // 获取主页面，核心数据
        String body = Jsoup.connect(newUrl).ignoreContentType(true).execute().body();
        // 获取列表
        String item_list = String.valueOf(JsonToMapUtil.toMap(body).get("item_list"));
        String substring = item_list.substring(1, item_list.length() - 1);
        String video = String.valueOf(JsonToMapUtil.toMap(substring).get("video"));
        String play_addr = String.valueOf(JsonToMapUtil.toMap(video).get("play_addr"));
        String url_list = String.valueOf(JsonToMapUtil.toMap(play_addr).get("url_list"));
        String play_url = url_list.substring(2, url_list.length() - 2);
        String videoUrl = (play_url.split("https://aweme.snssdk.com/aweme")[2].split("&ratio=720p&line=0")[1]).replace("playwm","play");
        String playUrl = "https://aweme.snssdk.com/aweme"+videoUrl+"&ratio=720p&line=0";
        String downLoad = DownloadUtil.download(playUrl);
        return downLoad;
    }

    /**
     * 解析html页面，
     * @return
     */
    /*
    public static String getDownloadUrl(String url) throws IOException {
        // 获取短连接码
        String sub = "https://v.douyin.com/"+url.split("https://v.douyin.com/")[1].substring(0, 7);
        // 通过短连接获取长链接
        String redirectUrl = Jsoup.connect(sub).followRedirects(true).execute().url().toString();
        try {
            //Parser parser = new Parser(redirectUrl);
            Parser parser = new Parser("https://www.douyin.com/video/7205178892632558885");
            HtmlPage htmlPage = new HtmlPage(parser);
            parser.visitAllNodesWith(htmlPage);
            TableTag[] tableTags = htmlPage.getTables();
            TableRow tableRows[] = tableTags[1].getRows();//tableTags[0]是单元号
            for (int i = 0; i < tableRows.length; i++) {
                TableColumn tableColumns[] = tableRows[i].getColumns();
                for (int j = 0; j < tableColumns.length; j++) {
                    String html = tableColumns[j].toHtml();
                    String regex = "'(.*?)'";
                    Pattern pattern = Pattern.compile(regex);
                    Matcher m = pattern.matcher(html);
                    List<String> list = new ArrayList<>();
                    while (m.find()) {
                        int k = 1;
                        String matchStr = m.group(k);
                        if(StringUtils.hasLength(matchStr)){
                            list.add(matchStr);
                        }
                        k++;
                    }
                    if (!CollectionUtils.isEmpty(list)) {
                        String outerId = list.get(0);
                        String name = tableColumns[j].toPlainTextString().trim();

                    }
                }
            }
        } catch (ParserException e) {
            e.printStackTrace();
        }
        return "";
    }
    */

    /**
     * 设置一个无头浏览器,抓取动态渲染页面
     * @param url 要解析页面URL地址
     * @return 返回Document对象
     */
    public static String accordingToURLGetBrowserHtml(String url) {
        // 获取短连接码
        String sub = "https://v.douyin.com/"+url.split("https://v.douyin.com/")[1].substring(0, 7);
        // 通过短连接获取长链接
        String requestUrl = null;
        try {
            requestUrl = Jsoup.connect(sub).followRedirects(true).execute().url().toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("正在加载页面: " + requestUrl);
        WebClient webClient = new WebClient(BrowserVersion.CHROME);//新建一个模拟谷歌Chrome浏览器的浏览器客户端对象
        webClient.getOptions().setJavaScriptEnabled(true); //很重要，启用JS
        webClient.getOptions().setCssEnabled(false);//是否启用CSS, 因为不需要展现页面, 所以不需要启用
        webClient.getOptions().setThrowExceptionOnScriptError(false);//当JS执行出错的时候是否抛出异常, 这里选择不需要
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);//当HTTP的状态非200时是否抛出异常, 这里选择不需要
        webClient.getOptions().setActiveXNative(false);//本地ActiveX
        webClient.getOptions().setTimeout(3 * 1000);//设置连接超时时间

        HtmlPage page = null;
        String pageXml = "";
        String playUrl = "";
        try {
            page = webClient.getPage(requestUrl);//加载异步ajax网页
            //webClient.waitForBackgroundJavaScript(3 * 1000);//异步JS执行需要耗时,所以这里线程要阻塞多少秒,看情况决定,等待异步JS执行结束
            webClient.setAjaxController(new NicelyResynchronizingAjaxController());//很重要，设置支持AJAX
            pageXml = page.asXml();//直接将加载完成的页面转换成xml格式的字符串
            //解码（前端传给后端数据，后端接收后要先 URLDecoder）
            int start=pageXml.indexOf("//<![CDATA[")+11;
            int end=pageXml.indexOf("//]]>");
            String cdata = pageXml.substring(start,end);
            String content= URLDecoder.decode(cdata, "UTF-8");
            //System.out.println(content);
            DouDataVO douDataVO = JSON.parseObject(content, DouDataVO.class);
            playUrl = douDataVO.getA44().getAweme().getDetail().getVideo().getPlayApi();
            if(StringUtils.hasLength(playUrl)){
                playUrl = "https://"+playUrl.substring(2);
            }
            //String coverUri = douDataVO.getA44().getAweme().getDetail().getVideo().getCoverUri();
            log.info("playUrl={}",playUrl);
            //log.info("coverUri={}",playUrl);
        } catch (Exception e) {
            log.error(e.getMessage());
            //e.printStackTrace();
        } finally {
            webClient.close();
        }
        //Document document = Jsoup.parse(pageXml);//Jsoup获取document对象
        return playUrl;
    }

    public static void main(String[] args) {
//        accordingToURLGetBrowserHtml("https://v.douyin.com/S6LM9MM/");
        accordingToURLGetBrowserHtml("https://v.douyin.com/S22Qaxk/");
    }
    public static void main1(String[] args) {
        try {
            downLoad("https://v.douyin.com/S6LM9MM/");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
